<?php
/**购物车控制器
 * @Author: 976123967@qq.com
 * @Date:   2014-09-08 21:33:17
 * @Last Modified by:   chen
 * @Last Modified time: 2014-09-08 23:38:14
 */
class CartControl extends CommonControl{


	// 用户uid
	private $uid;
	// 模型
	private $model;

	public function __auto()
	{
		$this->uid = isset($_SESSION['uid'])?$_SESSION['uid']:null;
		$this->model = K('Cart');

		// 登录了后 session 里的购物车信息移动到数据库中
		if($this->uid)
			$this->model->move_to_cart();
	}


	/**
	 * [index 购物车展示]
	 * @return [type] [description]
	 */
	public function index()
	{
		$data = $this->model->get_cart_format();
		$this->assign($data);
		$this->display();
	}


	/**
	 * [add_cart 添加商品到购物车]
	 */
	public function add_cart()
	{
		if(!IS_AJAX) return false;
		$gid = Q('post.gid',null,'intval');	
		// 用户没有登录
		if(is_null($this->uid))
		{
			$data = array(
				'id'=>$gid,
				'name'=>'',
				'num'=>1,
				'price'=>0
			);
			cart::add($data);
		}
		// 用户已经登录
		else
		{
			$data = array(
				'goods_id'=>$gid,
				'user_id'=>$this->uid,
				'goods_num'=>1,
			);
			$this->model->add_cart($data);
			
		}


		// 统计
		$total = $this->model->get_cart_count();
		$this->ajax(array('status'=>true,'total'=>$total));

	}
}